package cn.net.dpi.core.validation;

import cn.net.dpi.core.annotation.IsEnum;
import org.springframework.util.ObjectUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author dzcr
 */
public class IsEnumValidator implements ConstraintValidator<IsEnum, String> {

    private List<String> names;

    @Override
    public void initialize(IsEnum constraintAnnotation) {
        names = Optional.ofNullable(constraintAnnotation)
                .map(cons -> cons.enumType())
                .filter(Class::isEnum)
                .map(clazz -> clazz.getEnumConstants())
                .map(e -> Arrays.stream(e)
                        .map(Object::toString)
                        .collect(Collectors.toList()))
                .orElse(new ArrayList<>());
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        return !ObjectUtils.isEmpty(names) && names.contains(value);
    }
}
